module SOD
  
  class Dialog # see OS DialogContainers
    
    def initialize(title = "Default", scrollbars = true, w = 660, h = 580, l = 150, t = 150)
      @title = title
      @scrollbars = scrollbars
      @key = nil #registry key that stores dialog preferences (size, position)
      @width = w
      @height = h
      @left = l
      @top = t
      @resizable = false
      
      @webDialog = UI::WebDialog.new(@title, @scrollbars, @key, @width, @height, @left, @top, @resizable)
    end
    
  end
  
  class SOD_Dialog < Dialog
    
    def initialize(title = "Default", scrollbars = true, w = 660, h = 580, l = 150, t = 150)
      super
    end
    
    def add_callbacks
      @webDialog.add_action_callback("onLoad") { onLoad }
      @webDialog.add_action_callback("on_change_element") { |d, p| on_change_element(d, p) }
      @webDialog.add_action_callback("on_cancel") { onCancel }
    end
    
    def show
      if(@webDialog.visible?)
        @webDialog.bring_to_front
      else
        @webDialog.show
      end
    end
    
    def set_file(file)
      @path = Sketchup.find_support_file("SOD/tools/dialogs/html/" + file, "Plugins")
      @webDialog.set_file(@path, nil)
    end
    
    def set_element_value(name, value)
      if (name.nil?)
        puts "Dialog:  nil name passed to set_element_value"
      else
        #value.gsub!(/\n/, "\\n")
        puts value
        @webDialog.execute_script("setElementValue('" + name + "', '" + value + "')")
      end
    end
    
    def set_select_options(name, values)
      if (name.nil?)
        puts "Dialog:  nil name passed to set_select_options"
      else
        if (values.nil?)
          values = []
        end
        values_arg = ""
        if (not values.empty?)
          for i in 0...values.length
            if (values[i].nil?)
              values[i] = ""
            else
              values[i] = values[i].gsub(/'/, "%apos%")  # Encode any single quotes so that a JavaScript error is avoided
            end
            values_arg += values[i] + ","
          end
          values_arg = values_arg[0...values_arg.length - 1]
        end
          values_arg = values_arg.gsub(/,/, "%comma%")
		  puts values_arg
        @webDialog.execute_script("setSelectOptions('" + name + "', '" + values_arg + "')")
      end
    end
    
    def onCancel
      close
    end
    
  end
  
end
